from django import template
from django.template import Context, loader, RequestContext
from lxml import etree
import os
import json
import re
from core.models import *
from glue.models import *

from pybb.models import Forum, Topic, Post

register = template.Library()

@register.simple_tag
def collect(service,user):
  objs = UsersOfService(service) 
  msg = str(len(objs))
  msg += " users have collected this service in their local services."
  if(user.is_authenticated()):
    if(len(objs.filter(user = user))):
      msg += """<span class='btngray'
             style='float:right;margin:0px;'>"""
      msg += """<a href='/glue/collection/personal/' style="position:relative;left:-18px">
              you have already collected this service
            </a>"""
      msg += "</span>"
    else:
      msg += """<span class='btnblue' onclick='zoyoe.admin.Collect()'
             style='float:right;margin:0px;position:relative;left:-18px'>collect this service</span>"""
  else:
    msg += """<span class='btnblue' onclick='zoyoe.admin.Collect()'
             style='float:right;margin:0px;position:relative;left:-18px'>collect this service</span>"""
  return msg

@register.simple_tag
def discountservices():
  services = ServiceCore.objects.all()[:9]
  services_t = loader.get_template('glue/_service.html')
  context = Context({'SERVICES':services})
  return services_t.render(context)


@register.tag(name='glue_load_last_topics')
def glue_load_last_topics(parser, token):
    """
    Create new context variable pointed to the list of topics.
    
    Usage examples:
        
        {% glue_load_last_topics as last_topics with forum=forum.pk,order_by="updated" %}

    Available arguments for with clause:
        limit: limitation of number of loaded items
        category: primary key of category to load topics from
        forum: primary key of forum to load topics from
        order_by: the Topic field name to order the topic selection with. Default is "created"
    """

    try:
        tag_name, arg = token.contents.split(None, 1)
    except ValueError:
        raise template.TemplateSyntaxError, "%r tag requires arguments" % token.contents.split()[0]
    match = re.search(r'as\s+(\w+)(?:\s+with\s+(.+))?', arg)
    if not match:
        raise template.TemplateSyntaxError, "%r tag had invalid arguments" % tag_name
    name = match.group(1)

    limit = '10'
    category = '0'
    forum = '0'
    order_by='"created"'

    if match.group(2):
        args = dict([x.strip().split('=') for x in match.group(2).split(',')])
        if 'limit' in args:
            limit = args['limit']
        if 'forum' in args:
            forum = args['forum']
        if 'order_by' in args:
            order_by = args['order_by']

    return GlueLastTopicsNode(name, limit, forum, category, order_by)

class GlueLastTopicsNode(template.Node):
    def __init__(self, name, limit, forum, category, order_by):
        self.name = name
        self.limit = template.Variable(limit)
        self.forum = template.Variable(forum)
        self.category = template.Variable(category)
        self.order_by = template.Variable(order_by)

    def render(self, context):
        limit = self.limit.resolve(context)
        category = self.category.resolve(context)
        forum = self.forum.resolve(context)
        order_by = self.order_by.resolve(context)
        topics = Topic.objects.all().select_related().order_by('-' + order_by)
        if category:
            topics = topics.filter(forum__category__pk=category)
        if forum:
            topics = topics.filter(forum__pk=forum)
        context[self.name] = topics[:limit]
        return ''


